package cn.com.w.easy.excel.demo.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * java实现导出excel文件到浏览器
 */
@RestController
@RequestMapping("/export")
public class ExportController {


    @GetMapping("/test")
    public String test() {
        return "test";
    }

    /**
     * http://127.0.0.1:8088/demo/export/toBrowser
     *
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/toBrowser")
    public String toBrowser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pathname = "/Users/zhangxiaolong/Desktop/题目做题情况_1693896226688.xlsx";
        File file = new File(pathname);
        if (!file.exists()) {
            // 文件不存在，返回错误信息或其他处理逻辑
            return "fail";
        }

        String fileNameOfExport = "zxl.xlsx";

        // 设置文件类型为 Excel 格式
        response.setContentType("application/vnd.ms-excel");
        // 设置文件名
        response.setHeader("Content-Disposition", "attachment; filename=" + fileNameOfExport);

        // 读取文件数据并写入响应流
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            // 处理 IO 异常
            e.printStackTrace();
        }
        return "ok";
    }

}
